import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBC_Insert {

    public static void main1(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入名字");
        String name = scanner.next();
        System.out.println("请输入id");
        int id = scanner.nextInt();
        //JDBC需要通过以下步骤完成开发
        //1.创建并初始化一个数据库
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1234");
        //MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //mysqlDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        //2.和数据库服务器建立连接
        Connection connection = dataSource.getConnection();
        //3.构造sql语句
        String sql = "insert into student value(?,?)";

        PreparedStatement statement = connection.prepareStatement(sql);//预编译
        statement.setInt(1,id);
        statement.setString(2,name);
        //4.执行sql语句
        int ret = statement.executeUpdate();// update insert delete
        System.out.println(statement);
        //5.释放必要的资源
        statement.close();
        connection.close();
    }

    public static void main2(String[] args) throws SQLException {
        //创建初始化数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1234");
        //构造连接
        Connection connection = dataSource.getConnection();
        //构造sql
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        //执行sql
        ResultSet set = statement.executeQuery();
        //遍历结果集合
        while (set.next()) {
            //把set想象成一个表格,同时表格的有个表头,初始是,光标指在表的第一行上面
            //当光标指向某一行,可以通过getXXX方法来获得当前这一行的数据
            int id = set.getInt("id");
            String name = set.getString("name");
            System.out.println("id = " + id + "  name = " + name);
            //getXXX方法是取出这一行的指定列的数据,使用的方法要和该列的数据类型匹配
            //参数可以是第几列的下标,也可以是列名
        }
        //释放资源
        set.close();//set可以认为是查询结果的临时表
        statement.close();
        connection.close();
    }
}
